import React from 'react';
import PropTypes from 'prop-types';

import { isToutiao, isWechat } from '@facejs/macro';
import HocComponent from '@packages/face-runner/HocComponent';
import * as request from '@packages/lib-request';

/**
 * 渲染商品列表数据
 */
@HocComponent()
export default class RenderGoods extends React.Component {
    static propTypes = {
        api: PropTypes.string,
        historyApi: PropTypes.string,
        type: PropTypes.string,
        clickType: PropTypes.string,
        rName: PropTypes.string,
        tabId: PropTypes.string,
        render: PropTypes.func.isRequired,
    };

    state = {};

    componentDidMount() {
        this.fetch();
    }

    onPullDownRefresh = () => {
        this.fetch().then(() => {
            if (isWechat) {
                // TODO: 统一多端 API
                wx.stopPullDownRefresh();
            } else if (isToutiao) {
                // TODO: 统一多端 API
                wx.stopPullDownRefresh();
            } else {
                this.page.trigger('stopPullDownRefresh');
            }
        });
    };
    onReachBottom = () => {
        const { page } = this.state;
        this.fetch({ page: page + 1 });
    };

    /**
     * 请求新的数据
     */
    fetch = ({ page = 1 } = {}) => {
        let { api } = this.props;
        api = api.startsWith('//') ? 'https:' + api : api;
        return new Promise((resolve) => {
            request.get(api, { page }, (res) => {
                const { data } = res;
                this.setState(({ list }) => {
                    return {
                        list: page > 1 ? [...list, ...data.list] : data.list,
                        page,
                    };
                }, resolve);
            });
        });
    };

    render() {
        const { render } = this.props;
        const { list, page } = this.state;
        return render({ list, page });
    }
}
